package service

import (
	"git.supremind.info/product/box/vehicle/internal/dao"
	"git.supremind.info/product/box/vehicle/internal/dto"
	"git.supremind.info/product/box/vehicle/internal/middleware"
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// token生成器
func GenerateToken(c *gin.Context, user dao.UserInfoAuth) {

	// 构造SignKey: 签名和解签名需要使用一个值
	j := middleware.NewJWT()

	// 构造用户claims信息(负荷)
	claims := middleware.CustomClaims{user.AuthCode,
		jwtgo.StandardClaims{
			NotBefore: time.Now().Unix() - 1000, // 签名生效时间
			ExpiresAt: time.Now().Unix() + 3600, // 签名过期时间
			Issuer:    "bgbiao.top",             // 签名颁发者
		},
	}

	// 根据claims生成token对象
	token, err := j.CreateToken(claims)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": -1, "message": err.Error()})
	}

	userInfo := dao.SelectUserInfoById(user.UserId)
	userCompanys := dao.SelectUserCompanyByExample(&dao.UserCompany{UserId: userInfo.ID})

	// 获取用户相关数据
	data := dto.LoginUserInfoDto{
		ID:       user.ID,
		UserId:   userInfo.ID,
		RealName: userInfo.RealName,
		Enabled:  true,
		AuthCode: user.AuthCode,
		Token:    token,
	}
	if userCompanys != nil && len(*userCompanys) != 0 {
		data.Company = userCompanys
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "message": "登陆成功", "data": data})
}
